﻿using Mysoft.Map.Extensions.DAL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace Mysoft.QuickCode.DAL.Tool
{
    /// <summary>
    /// 小平头实体辅助工具
    /// </summary>
    public static class BaseEntityUtil
    {
        /// <summary>
        /// 处理默认值，可以用于更新前处理数据库默认不会更新的小平台默认值字段
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        public static void SetDefaultValues<T>(T entity)
            where T : BaseEntity
        {
            Type entityType = entity.GetType();
            object defaultEntity = Activator.CreateInstance(entityType, false);
            //取所有属性对应的表字段映射
            PropertyInfo[] props = entityType.GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
            foreach (var pi in props)
            {
                var value1 = pi.GetValue(entity, null);
                var value2 = pi.PropertyType.IsValueType ? Activator.CreateInstance(pi.PropertyType) : null;

                if (pi.PropertyType.IsValueType && value1 == null && value2 == null)
                {
                    entity.SetPropertyDefaultValue(pi.Name);
                }
                else if (pi.PropertyType.IsValueType && value2 != null && value2.Equals(value1))
                {
                    entity.SetPropertyDefaultValue(pi.Name);
                }
            }
        }
    }
}
